package ethvlans

import (
	"encoding/json"
	"strconv"
	"strings"
)

// String 格式化为字符串
func (v EthVLANs) String() string {
	ints := v.Slice()
	if ints == nil || len(ints) == 0 {
		return ""
	}
	if len(ints) == 1 {
		return strconv.Itoa(ints[0])
	}

	var (
		b         strings.Builder
		willWrite = true
		prev      = -1
	)

	for _, n := range ints {
		if prev == -1 {
			prev = n
			continue
		}

		if willWrite {
			b.WriteString(strconv.Itoa(prev))
			if n-prev == 1 {
				b.WriteByte('-')
				willWrite = false
				prev = n
				continue
			}

		} else {
			if n-prev == 1 {
				prev = n
				continue
			} else {
				b.WriteString(strconv.Itoa(prev))
				willWrite = true
			}
		}
		prev = n
		b.WriteByte(',')
	}
	b.WriteString(strconv.Itoa(ints[len(ints)-1]))
	return b.String()
}

// MarshalJSON implements the interface MarshalJSON for json.Marshal.
func (v EthVLANs) MarshalJSON() ([]byte, error) {
	return json.Marshal(v.String())
}

// UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal.
func (v EthVLANs) UnmarshalJSON(b []byte) error {
	var s string
	if err := json.Unmarshal(b, &s); err != nil {
		return err
	}
	v = Parse(s)

	return nil
}
